package com.example.second.service;

import com.alibaba.fastjson.JSON;
import com.example.second.dao.IOrderDao;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class OrderServiceImpl implements IOrderService{

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    IOrderDao iOrderDao;
    private Random random = new Random(1);

    public Map<String,Object> createOrder(String sku_id,String user_id){
        Map<String,Object> resultMap = new HashMap<String, Object>();

        if(sku_id==null||sku_id.equals("")){
            resultMap.put("result",false);
            resultMap.put("msg", "商品信息有误");
            return resultMap;
        }

        String order_id = String.valueOf(System.currentTimeMillis())+random.nextInt(9)+random.nextInt(9)+random.nextInt(9)+random.nextInt(9)+random.nextInt(9);
        String policy = stringRedisTemplate.opsForValue().get("LIMIT_POLICY_"+sku_id  );

        if(policy!=null&&!policy.equals("")){
            //判断是否在秒杀活动期内
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Map<String,Object> policyInfo = JSON.parseObject(policy, Map.class);

            try {
                Date begin = simpleDateFormat.parse(policyInfo.get("begin_time").toString());
                Date end = simpleDateFormat.parse(policyInfo.get("end_time").toString());
                String nowstring = restTemplate.getForObject("http://time-server/gettime",String.class);
                Date now = simpleDateFormat.parse(nowstring);
                if(now.getTime()<begin.getTime()){
                    resultMap.put("result",false);
                    resultMap.put("msg", "活动尚未开始");
                    return resultMap;
                }else if(now.getTime()>end.getTime()){
                    resultMap.put("result",false);
                    resultMap.put("msg", "活动已过期");
                    return resultMap;
                }else {
                    //redis计数器限流
                    long limitQuanty = Long.parseLong(policyInfo.get("quanty").toString());

                    if(stringRedisTemplate.opsForValue().increment("LIMIT_QUANTY_"+sku_id, 1)<=limitQuanty){
                        Map<String,Object> orderInfo = new HashMap<String, Object>();
                        Map<String,Object> skuMap = JSON.parseObject(stringRedisTemplate.opsForValue().get("SKU_"+sku_id).toString(),Map.class);

                        orderInfo.put("order_id", order_id);
                        orderInfo.put("total_fee", skuMap.get("price"));
                        orderInfo.put("actual_fee", policyInfo.get("price"));
                        orderInfo.put("post_fee", 0);
                        orderInfo.put("payment_type", 0);
                        orderInfo.put("user_id", user_id);
                        orderInfo.put("status", 1);
                        orderInfo.put("create_time", nowstring);

                        orderInfo.put("sku_id", sku_id);
                        orderInfo.put("num", 1);
                        orderInfo.put("title", skuMap.get("title"));
                        orderInfo.put("own_spec", skuMap.get("own_spec"));
                        orderInfo.put("price", policyInfo.get("price"));
//                        orderInfo.put("image", skuMap.get("images"));
                        try {
                            String order = JSON.toJSONString(orderInfo);
                            amqpTemplate.convertAndSend("order_queue", order);
                            stringRedisTemplate.opsForValue().set("ORDER_"+order_id, order);
                        }catch (Exception exception){
                            resultMap.put("result",false);
                            resultMap.put("msg", "队列写入失败");
                            return resultMap;
                        }

                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }else {
            resultMap.put("result",false);
            resultMap.put("msg", "活动已过期");
            return resultMap;
        }

        resultMap.put("result",true);
        resultMap.put("msg", "成功生成订单");
        resultMap.put("order_id", order_id);
        return resultMap;
    }

    //从订单队列中拿到订单后写入mysql数据库
    public Map<String,Object> insertOrder(Map<String,Object> orderInfo){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(orderInfo==null||orderInfo.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "参数有误");
            return resultMap;
        }
        if(iOrderDao.insertOrder(orderInfo)){
            resultMap.put("result", true);
            resultMap.put("msg", "成功插入数据库");
            return resultMap;
        }
        resultMap.put("result", false);
        resultMap.put("msg", "插入数据库失败");
        return resultMap;
    }

    public Map<String, Object> getOrder(String order_id){
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (order_id==null||order_id.equals("")){
            resultMap.put("result", false);
            resultMap.put("msg", "参数传入有误！");
            return resultMap;
        }

        ArrayList<Map<String, Object>> list = iOrderDao.getOrder(order_id);
        resultMap.put("order", list);
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }

    public Map<String, Object> payOrder(String order_id,String sku_id){

        Map<String,Object>    resultMap = new HashMap<String, Object>();
        if(order_id==null||order_id==""){
            resultMap.put("result", false);
            resultMap.put("msg", "订单号有误");
            return resultMap;
        }
        //这个地方老出问题，能不被先写入消息队列，然后在消费者那边改mysql中的订单状态
//        boolean result = iOrderDao.updateOrderStatus(order_id);

//        if(!result){
//            resultMap.put("result", false);
//            resultMap.put("msg", "订单状态更新失败,尚未发送到库存队列");
//            return resultMap;
//        }
        Map<String,Object>  ordermsg = new HashMap<String, Object>();
        ordermsg.put("sku_id", sku_id);
        ordermsg.put("order_id", order_id);

        amqpTemplate.convertAndSend("storage_queue", JSON.toJSONString(ordermsg));
        resultMap.put("result", true);
        resultMap.put("msg", "写入库存更新队列");
        return resultMap;
    }
}
